from odoo import fields, models, api
from ...functions.marketing_schedule_func import MarketingScheduleFunc


class RpMarketingManualScheduleTran(models.TransientModel):
    _name = 'rp.marketing.manual.schedule.tran'
    _description = '手动任务'

    def _default_code(self):
        records = self.env['rp.marketing.manual.schedule.tran'].search([])
        return "MST" + str(len(records) + 1).zfill(3)

    code = fields.Char(string='序列号', default=_default_code, index=True, readonly=True)
    operation_person = fields.Many2one(string='操作人', comodel_name='res.users', default=lambda self: self.env.user)
    category_tag = fields.Boolean(string='分类', default=False)
    customer_category_ids = fields.Many2many(string='用户分类', comodel_name='rp.customer.category', column1='manual_schedule_id', column2='customer_category_id',
                                             relation='manual_schedule_customer_category_rel')
    level_tag = fields.Boolean(string='等级', default=False)
    customer_level_ids = fields.Many2many(string='用户等级', comodel_name='rp.customer.level', column1='manual_schedule_id', column2='customer_category_id',
                                          relation='manual_schedule_customer_level_rel')
    customer_tag = fields.Boolean(string='客户', default=False)
    rp_customer_ids = fields.Many2many(string='指定用户', comodel_name='rp.customer', column1='manual_schedule_id', column2='rp_customer_id'
                                       , relation='manual_schedule_rp_customer_rel')
    manual_coupon_issue_line_ids = fields.One2many(string='发放优惠券', comodel_name='rp.manual.schedule.coupon.issue.line', inverse_name='manual_schedule_tran_id')
    price_change_type = fields.Selection(string='变动类型', selection=[('add', '充值'), ('subtract', '扣减')], default='add')
    cash_back_price = fields.Float(string='变动')
    currency_id = fields.Many2one(string='货币单位', comodel_name='res.currency', default=lambda self: self.env.company.currency_id)
    create_datetime = fields.Datetime(string='创建时间', default=fields.Datetime.now(), index=True)

    @api.onchange('category_tag', 'level_tag', 'customer_tag')
    def onchange_tag(self):
        if not self.category_tag:
            self.update({'rp_customer_ids': False, 'customer_category_ids': False})
        if not self.level_tag:
            self.update({'customer_level_ids': False, 'rp_customer_ids': False})
        if not self.customer_tag:
            self.update({'rp_customer_ids': False})

    @api.onchange('customer_category_ids', 'customer_level_ids')
    def onchange_category_level_customer(self):
        domain_list = []
        if len(self.customer_category_ids.ids) > 0:
            domain_list.append(('rp_customer_category', 'in', self.customer_category_ids.ids))
        if len(self.customer_level_ids.ids) > 0:
            domain_list.append(('customer_level', 'in', self.customer_level_ids.ids))
        return {'domain': {'rp_customer_ids': domain_list}}

    def execute_the_manual_schedule(self):
        """
        执行手动任务
        """
        self.ensure_one()
        domain_list = MarketingScheduleFunc(self.env, self).build_domain(self.customer_category_ids.ids, self.customer_level_ids.ids, self.rp_customer_ids.ids)
        customer_ids = self.env['rp.customer'].search(domain_list)
        for customer in customer_ids:
            # 返回优惠券和现金
            MarketingScheduleFunc(self.env, self).manual_issue_coupon_and_cash(customer, self.price_change_type, self.cash_back_price, self.manual_coupon_issue_line_ids)
        # 记录任务日志
        MarketingScheduleFunc(self.env, self).record_the_schedule_log(customer_ids=customer_ids, price_change_type=self.price_change_type,
                                                                      cash_back_price=self.cash_back_price, coupon_issue_line_ids=self.manual_coupon_issue_line_ids, operation_person=self.operation_person, operation_type='manual')


class RpManualScheduleCouponIssueLine(models.TransientModel):
    _name = 'rp.manual.schedule.coupon.issue.line'
    _description = '优惠券明细'

    manual_schedule_tran_id = fields.Many2one(string='关联主表', comodel_name='rp.marketing.manual.schedule.tran')
    rp_coupon_template_id = fields.Many2one(string='优惠券模板', comodel_name='rp.marketing.coupon.template')
    name_display = fields.Char(string='名称', compute='depends_template_amount', store=True)
    amount = fields.Integer(string='数量')

    @api.depends('rp_coupon_template_id', 'amount')
    def depends_template_amount(self):
        for record in self:
            if all([record.rp_coupon_template_id, record.amount]):
                record.write({'name_display': f'{record.rp_coupon_template_id.name}*{record.amount}'})
            else:
                record.write({'name_display': 'NEW'})
